package com.ruoyi.wb.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.wb.domain.*;
import com.ruoyi.wb.enmus.RoleNameEnums;
import com.ruoyi.wb.enmus.WbEntAuthType;
import com.ruoyi.wb.mapper.WbContractMapper;
import com.ruoyi.wb.mapper.WbEntAuthMapper;
import com.ruoyi.wb.service.IWbEntAuthService;
import com.ruoyi.wb.service.IWbFireServiceUnitService;
import com.ruoyi.wb.service.IWbMaintainCompanyService;
import com.ruoyi.wb.service.IWbPlanService;
import com.ruoyi.wb.vo.WbEntAuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 企业认证Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class WbEntAuthServiceImpl implements IWbEntAuthService 
{
    @Autowired
    private WbEntAuthMapper wbEntAuthMapper;

    @Autowired
    private WbContractMapper wbContractMapper;

    @Autowired
    private IWbPlanService iWbPlanService;

    @Autowired
    private IWbMaintainCompanyService iWbMaintainCompanyService;

    @Autowired
    private IWbFireServiceUnitService wbFireServiceUnitService;
    /**
     * 查询企业认证
     * 
     * @param id 企业认证主键
     * @return 企业认证
     */
    @Override
    public WbEntAuth selectWbEntAuthById(Long id)
    {
        return wbEntAuthMapper.selectWbEntAuthById(id);
    }

    /**
     * 查询企业认证列表
     * 
     * @param wbEntAuth 企业认证
     * @return 企业认证
     */
    @Override
    public List<WbEntAuth> selectWbEntAuthList(WbEntAuth wbEntAuth)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        List<SysRole> roles = user.getRoles();
        for (SysRole sysRole : roles) {
            if (sysRole.getRoleName().equals(RoleNameEnums.MAINTAIN_ADMIN.getDescribe())) {//如果是业务员 则只能看到自己维保公司的数据
                List<WbMaintainCompany> wbMaintainCompanies = iWbMaintainCompanyService.selectWbMaintainCompanyByUserId(user.getUserId());
                if (!CollectionUtils.isEmpty(wbMaintainCompanies)){
                    WbMaintainCompany wbMaintainCompany = wbMaintainCompanies.get(0);
                    wbEntAuth.setMaintainCompanyId(wbMaintainCompany.getId());
                    return  wbEntAuthMapper.selectWbEntAuthList(wbEntAuth);
                }

            }
        }
        return wbEntAuthMapper.selectWbEntAuthList(wbEntAuth);
    }

    /**
     * 新增企业认证
     * 
     * @param wbEntAuth 企业认证
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWbEntAuth(WbEntAuth wbEntAuth)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        //查询当前用户是不是维保公司管理员
        List<SysRole> roles = user.getRoles();
        boolean flag=false;
        for (SysRole sysRole : roles) {
            if (sysRole.getRoleName().equals(RoleNameEnums.ADMIN.getDescribe())||sysRole.getRoleName().equals(RoleNameEnums.PTGLY.getDescribe())) {//超级管理员
                flag=true;
              break;
            }else if (sysRole.getRoleName().equals(RoleNameEnums.MAINTAIN_ADMIN.getDescribe())){// 维保公司管理员
                flag=true;
            }

        }

      if (flag) {
          //查询自己维保公司
          List<WbMaintainCompany> wbMaintainCompanies = iWbMaintainCompanyService.selectWbMaintainCompanyByUserId(user.getUserId());
          if (!CollectionUtils.isEmpty(wbMaintainCompanies)) {
              WbMaintainCompany wbMaintainCompany = wbMaintainCompanies.get(0);
              wbEntAuth.setMaintainCompanyId(wbMaintainCompany.getId());
          }
          wbEntAuth.setState(WbEntAuthType.VERIFIED.getCode());
          wbEntAuth.setCreateTime(DateUtils.getNowDate());
          int i = wbEntAuthMapper.insertWbEntAuth(wbEntAuth);
          if (i == 0) {
              throw new RuntimeException("插入企业认证失败");
          }
          return i;
      }
      return 0;
//        //先查询是否认证过
//        List<WbEntAuth> wbEntAuthList = wbEntAuthMapper.selectWbEntAuthListByUserId(loginUser.getUserId(), null);
//        List<WbEntAuth> collect = wbEntAuthList.stream().filter(item -> !(item.getState().equals(WbEntAuthType.REJECT.getCode()))|| ObjectUtils.isEmpty(item.getState())).collect(Collectors.toList());
//       //如果有状态不是驳回的 说明已经认证过企业 则不让认证
//        if (!CollectionUtils.isEmpty(collect)){
//            return 0;
//        }
//
//
//
//
//        wbEntAuth.setState(WbEntAuthType.UNDER_REVIEW.getCode());
//
//        wbEntAuth.setCreateTime(DateUtils.getNowDate());
//
//        int i = wbEntAuthMapper.insertWbEntAuth(wbEntAuth);
//        if (i==0){
//            throw new RuntimeException("插入企业认证失败");
//        }
//
//        //新增企业认证的同时 新增用户和企业关联表
//        WbUserEntAuth wbUserEntAuth = new WbUserEntAuth();
//        wbUserEntAuth.setSysUserId(loginUser.getUserId());
//        wbUserEntAuth.setWbEntAuthId(wbEntAuth.getId());
//        wbUserEntAuth.setCreateUser(loginUser.getUsername());
//        wbUserEntAuth.setUpdateUser(loginUser.getUsername());
//        wbUserEntAuth.setCreateTime(DateUtils.getNowDate());
//        wbUserEntAuth.setUpdateTime(DateUtils.getNowDate());
//        int j = wbUserEntAuthMapper.insertWbUserEntAuth(wbUserEntAuth);
//        if (j==0){
//            throw new RuntimeException("插入用户企业关联表失败");
//        }
//        return i;
    }

    /**
     * 修改企业认证
     * 
     * @param wbEntAuth 企业认证
     * @return 结果
     */
    @Override
    public int updateWbEntAuth(WbEntAuth wbEntAuth)
    {
        wbEntAuth.setUpdateTime(DateUtils.getNowDate());
        return wbEntAuthMapper.updateWbEntAuth(wbEntAuth);
    }

    /**
     * 批量删除企业认证
     * 
     * @param ids 需要删除的企业认证主键
     * @return 结果
     */
    @Override
    public int deleteWbEntAuthByIds(Long[] ids)
    {
        return wbEntAuthMapper.deleteWbEntAuthByIds(ids);
    }

    /**
     * 删除企业认证信息
     * 
     * @param id 企业认证主键
     * @return 结果
     */
    @Override
    public int deleteWbEntAuthById(Long id)
    {
        return wbEntAuthMapper.deleteWbEntAuthById(id);
    }

    /**
     * 查询客户信息
     * @param wbEntAuth
     * @param userId
     * @return
     */
    @Override
    public List<WbEntAuth> selectClientInfoPage(WbEntAuth wbEntAuth, Long userId) {
        WbPlan plan = new WbPlan();
        plan.setOperaterId(userId);
        List<WbPlan> wbPlans = iWbPlanService.selectWbPlanList(plan);
        if (CollectionUtils.isEmpty(wbPlans)) {
            return Collections.emptyList();
        }
        Set<Long> set = wbPlans.stream().map(WbPlan::getClientId).collect(Collectors.toSet());
        wbEntAuth.setClientIdList(set);
        return wbEntAuthMapper.selectWbEntAuthList(wbEntAuth);
    }

    @Override
    public List<WbEntAuth> selectWbEntAuthListByUserId(Long userId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        List<WbEntAuth> wbEntAuths = new ArrayList<>();
        //查询当前用户是否有合同 如果有合同则采用合同上的维保公司
        List<WbContract> wbContract= wbContractMapper.selectContractByUserPhone(user.getPhonenumber());
        if (!CollectionUtils.isEmpty(wbContract)){
            WbEntAuth wbEntAuth = wbEntAuthMapper.selectWbEntAuthById(wbContract.get(0).getClientId());
            if (!ObjectUtils.isEmpty(wbEntAuth)){
                wbEntAuths.add(wbEntAuth);
            }
        }
        return wbEntAuths;
    }

    //查询维保公司 下的业主公司
    @Override
    public List<WbEntAuthVo> listEntAuthWb(WbEntAuth wbEntAuth) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //维保公司只能查看自己维保公司企业
        List<WbMaintainCompany> wbMaintainCompanies = iWbMaintainCompanyService.selectWbMaintainCompanyByUserId(user.getUserId());
        if (!CollectionUtils.isEmpty(wbMaintainCompanies)){
            WbMaintainCompany wbMaintainCompany = wbMaintainCompanies.get(0);
            wbEntAuth.setMaintainCompanyId(wbMaintainCompany.getId());
        }
        //如果是消防单位 则只能看见自己单位省市区下的企业
        WbFireServiceUnit fireServiceUnit =  wbFireServiceUnitService.getFireServiceUnitByUserId(user.getUserId());
        if (!ObjectUtils.isEmpty(fireServiceUnit)){
            if(ObjectUtils.isEmpty(fireServiceUnit.getProvince())){
                return new ArrayList<WbEntAuthVo>();
            }
            if (!ObjectUtils.isEmpty(fireServiceUnit.getProvince())){
                wbEntAuth.setProvince(fireServiceUnit.getProvince());
                wbEntAuth.setCity(null);
                wbEntAuth.setCounty(null);
            }
            if (!ObjectUtils.isEmpty(fireServiceUnit.getCity())){
                wbEntAuth.setCity(fireServiceUnit.getCity());
                wbEntAuth.setCounty(null);
            }
            if (!ObjectUtils.isEmpty(fireServiceUnit.getCounty())){
                wbEntAuth.setCounty(fireServiceUnit.getCounty());
            }
        }
        startPage();
        return wbEntAuthMapper.listEntAuthWb(wbEntAuth);
    }
}
